<template>
  <div class="indexAnalysis-container" v-if="!notDataImage">
    <van-nav-bar
      :title="
        this.operationContent[this.operationContent.length - 1] === 'drill'
          ? '下钻分析'
          : this.operationContent[this.operationContent.length - 1] === 'attribution'
          ? '归因分析'
          : '交叉分析'
      "
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
      v-if="!$isDD"
    />
    <div class="data_container" :class="!$isDD ? 'indexAnalysisData_container' : ''" @touchmove="handleTouch">
      <detailData
        :fieldsDimlogicCode="fieldsDimlogicCode"
        :data="defineData"
        :filterData="filterData"
        :trackParame="trackParame"
        :tendencyData="tendencyData"
        :dateType="dateType"
        @istracked_="istracked_"
        :istracked="istracked"
        @secondaryNumber="secondaryNumber"
        @getIndex="handleIndex"
        @indexModifyPopup="handleModifyPopup"
        :titleDimContent="titleDimContent"
        @getSortIndex="handleSortIndex"
        :DetailDataJson="DetailDataJson"
        :echartsRadarData.sync="echartsRadarData"
        @tendencyDateChange="tendencyDateChange"
        @getAttribution="getAttribution"
        :operation="operationContent"
      ></detailData>
      <detailPopup
        :isShowPopup.sync="isShowPopup"
        @closeDetailPup="handleCloseDetailPup"
        @handleTrackButtonIn="handleTrackButtonIn"
        @handleTrackButtonOut="handleTrackButtonOut"
        @overLappingPuPDetermine="handleOverLappingPuPDetermine"
        @drilldownPuPDetermine="handleDrilldownPuPDetermine"
        @getAttribution="getAttribution"
        :overlapingItem="overlapingItem"
        :fields="defineData.fields || {}"
        :pupValue="pupValue"
        :dataContent="dataContent"
        :dataType="primaryDataType"
        :modifyPup.sync="modifyPup"
        :header="defineData.header || {}"
        :titleDimContent="titleDimContent"
        :modifyFilter="modifyFilter"
        :buttonType="buttonType"
        :operationType="operationType"
        :DetailDataJson="DetailDataJson"
        :trackStatusnum="trackStatusnum"
        :trackParame="trackParame"
        :filterData="filterData"
        :detailsIstracked="detailsIstracked"
      ></detailPopup>
      <div class="noListTable" v-show="defineData.nolistTable === true">已经到底啦~</div>
    </div>
  </div>
  <div v-else class="noData-container">
    <img src="@/assets/images/no-data.png" alt="" class="noData" />
    <div class="noDataMessage">暂无数据，请切换数据维度</div>
  </div>
</template>

<script>
import {
  getDetailData,
  getDimOptionsData,
  queryTendencyData,
  queryAttribution,
  traceStatus,
  saveFeeds
} from '@/api/home'
import detailData from './detailData.vue'
import detailPopup from './detailPopup.vue'
import sensormixin from '@/mixins'
import _ from 'lodash'
export default {
  mixins: [sensormixin],
  data() {
    return {
      istracked: true, //  false已经被追踪
      secondaryNum: 0,
      detailsIstracked: false, // 详情维度的追踪状态
      trackStatusnum: 0,
      DetailDataJson: {
        dateType: '',
        topic: '',
        id: '',
        queryDate: '',
        operation: 'drill',
        targetCode: '',
        filters: [],
        page: 1,
        size: 200,
        sort: 'DESC',
        sortField: '',
        fields: []
      }, // 请求参数
      operationType: '',
      lastOperation: '',
      buttonType: '',
      notDataImage: false,
      fieldsDimlogicCode: '', // 主指标logicCode
      trackParame: {},
      isShowPopup: false, // 是否展示弹窗
      dataContent: [], // 交叉存储数据数组。最后一个赋值给defineData展示
      defineData: {}, // 交叉展示数据
      primaryDataType: '', // 主指标类型
      overlapingItem: {}, // 列表点击单个数据
      pupValue: [], // 弹窗选择列表
      idContent: [], // id集合
      operationContent: [], // 存储下钻交叉数组
      filterData: [], // 存放filters参数的集合
      refCodeData: '', // 点击的code
      modifyPup: 0, // 选择的是哪个按钮（下钻，交叉，追踪）
      modifyFilter: false, // 是否点击的是修改按钮
      titleDimContent: [], // 维度标题展示，
      filedActiveId: [],
      listContent: [], // 存放加载更多数据
      tendencyData: null, // 趋势图数据
      dateType: 'year',
      dateTypes: [],
      attributionFilter: [],
      echartsRadarData: {
        reference: [],
        indicator: []
      },
      echartsRadarDataContent: []
    }
  },
  components: {
    detailData,
    detailPopup
  },
  created() {
    if (this.$isDD) {
      this.$dd.ui.webViewBounce.disable()
      this.$dd.ready(() => {
        this.$dd.biz.navigation.setTitle({
          title:
            this.operationContent[this.operationContent.length - 1] === 'drill'
              ? '下钻分析'
              : this.operationContent[this.operationContent.length - 1] === 'attribution'
                ? '归因分析'
                : '交叉分析'
        })

        if (this.$dd.android) {
          document.addEventListener('backbutton', e => {
            // 在这里处理你的业务
            this.dataCtl()
            // 安卓调用方式
            e.preventDefault() // 阻止返回
          })
        } else {
          this.$dd.biz.navigation.setLeft({
            control: true,
            text: '',
            onSuccess: result => {
              // IOS调用方法 ios返回不起作用，需要手动让他返回window.history.go(-1)
              this.dataCtl()
            },
            onFail(err) {
              console.log('返回失败', err)
            }
          })
        }
      })
    }
  },
  mounted() {
    /**
     * ASC 表示从小到大排序
     * DESC 表示从大到小排序
     * sortField 默认给targetCode值。点击指标或者参考系的时候，变成点击值的code
     * */
    this.getqueryUrl()
    this.getDetailData(this.DetailDataJson)
    this.getTendencyData(this.DetailDataJson)
    const pageOperation = this.currentPageOperation()
    if (pageOperation === 'drill') {
      // 下钻埋点
      this.drillDownToAnalyse(
        { fields: this.filedActiveId, filters: [] },
        { targetCode: this.DetailDataJson.targetCode }
      )
    } else if (pageOperation === 'pivot') {
      // 交叉埋点
      this.crossToAnalyse({ fields: this.filedActiveId, filters: [] }, { targetCode: this.targetCode })
    }

    // 监听滑动
    window.addEventListener('scroll', this.handleScroll)
  },
  watch: {
    operationContent(newval) {
      this.setTitle(newval[this.operationContent.length - 1])
      console.log('watch,operationContent:', JSON.stringify(newval))
    },
    filedActiveId(newval) {
      console.log('watch,filedActiveId:', JSON.stringify(newval))
    },
    filterData(newval) {
      console.log('watch,filterData:', JSON.stringify(newval))
    }
  },
  methods: {
    currentPageOperation() {
      return this.operationContent[this.operationContent.length - 1]
    },
    handleTrackButton() {},
    secondaryNumber(num) {
      this.secondaryNum = num
    },
    istracked_() {
      this.istracked = true
    },
    async handleTrackButtonIn() {
      this.detailsIstracked = true
    },
    async handleTrackButtonOut() {
      const status =
        ['', null, 'null'].includes(this.trackParame.indexValue) &&
        ['', null, 'null'].includes(this.trackParame.comparedValue)
      if (status) {
        this.$toast('该数据不能被追踪')
        return
      }
      const data = await saveFeeds(this.trackParame)
      if (data.success && data.value.addFlag === '0') {
        this.$toast('已追踪，请至"我的"页面查看')
        this.istracked = true
      }
    },
    // 设置标题
    setTitle(title) {
      if (this.$isDD) {
        this.$dd.ready(() => {
          this.$dd.biz.navigation.setTitle({
            title: title === 'drill' ? '下钻分析' : title === 'attribution' ? '归因分析' : '交叉分析'
          })
        })
      }
    },
    // 获取单个列表信息 istracked 追踪状态， true已经被追踪
    async handleIndex(isOpenPopup, overlapingItem, filterData, operation) {
      this.isShowPopup = isOpenPopup // 打开弹窗
      this.overlapingItem = overlapingItem
      this.refCodeData = filterData
      this.modifyFilter = false
      this.buttonType = 'itemButton'
      const scalePremYtd = this.defineData.fields.find(item => item.role === 'measure' && item.type === 'primary')
        ?.logicCode
      const scalePremYoy = this.defineData.fields.find(item => item.role === 'measure' && item.type === 'secondary')
        ?.logicCode
      const orgBranchs = this.defineData.fields.filter(item => item.role === 'dim')
      const dimensionInfosExtra = orgBranchs.map(orgBranch => {
        return {
          code: orgBranch.refCode,
          value: overlapingItem[orgBranch.refCode],
          name: overlapingItem[orgBranch.logicCode]
        }
      })
      this.trackParame = {
        snapshotTime: this.DetailDataJson.queryDate,
        comparedValue: overlapingItem[scalePremYoy],
        avatorUrl: this.userInfo?.avatar,
        indexValue: overlapingItem[scalePremYtd],
        summarizingKey: this.DetailDataJson.targetCode,
        dateType: this.DetailDataJson.dateType,
        dimensionInfoList: this.filterData.concat(dimensionInfosExtra)
      }
      const res = await traceStatus(this.trackParame)
      this.detailsIstracked = res.value
      this.getPupOptionData()
    },
    /** 排序 */
    handleSortIndex(code, fieldCode) {
      this.modifyFilter = true
      this.DetailDataJson.sortField = code
      this.DetailDataJson.page = 1
      this.listContent = []
      this.DetailDataJson.id = this.idContent[this.idContent.length - 1]
      this.DetailDataJson.fields =
        this.operationContent[this.operationContent.length - 1] === 'drill'
          ? this.filedActiveId.slice(-1)
          : this.filedActiveId.slice(-2)
      this.DetailDataJson.filters = [...this.filterData]
      this.DetailDataJson.operation = this.operationContent[this.operationContent.length - 1]
      fieldCode.map(item => {
        if (item.code === code) {
          item.sortUp === true ? (this.DetailDataJson.sort = 'ASC') : (this.DetailDataJson.sort = 'DESC')
        }
      })
      this.getDetailData(this.DetailDataJson)
    },
    // 修改
    handleModifyPopup(isPopup, operation, buttonType) {
      if (operation === 'drill' || operation === 'attribution') {
        this.modifyPup = 3
      } else if (operation === 'pivot') {
        this.modifyPup = 1
      }
      this.buttonType = buttonType
      this.operationType = operation
      this.isShowPopup = isPopup
      this.modifyFilter = true
      this.getPupOptionData()
      this.trackParame = this.getCurrentTrackParams()
    },
    // 关闭弹窗
    handleCloseDetailPup(data) {
      // this.isShowPopup = data
      this.modifyPup = 0
    },
    initOpertion(operation) {
      this.operationContent.push(operation)
      console.log('watch, initOpertion', operation, this.operationContent)
      this.DetailDataJson.operation = operation
    },
    // 获取路径参数
    getqueryUrl() {
      const {
        dateType,
        topic,
        targetCode,
        id,
        date,
        mkt_org_branch,
        mkt_org_cen_branch,
        mkt_org_busi_branch,
        companyName
      } = this.$route.query
      if (
        !id ||
        id === 'null' ||
        id === 'undefined' ||
        !date ||
        date === 'null' ||
        date === 'undefined' ||
        !dateType ||
        dateType === 'null' ||
        dateType === 'undefined'
      ) {
        this.notDataImage = true
        return
      }
      if (companyName !== '' && companyName !== '全司') {
        this.titleDimContent.push(companyName)
      }
      this.dateType = dateType
      this.dateTypes.push(dateType)
      this.DetailDataJson.dateType = dateType
      this.DetailDataJson.topic = topic
      this.DetailDataJson.targetCode = targetCode
      this.DetailDataJson.queryDate = date
      this.DetailDataJson.id = id
      mkt_org_branch ? this.filterData.push({ code: 'mkt_org_branch', value: mkt_org_branch }) : ''
      mkt_org_cen_branch ? this.filterData.push({ code: 'mkt_org_cen_branch', value: mkt_org_cen_branch }) : ''
      mkt_org_busi_branch ? this.filterData.push({ code: 'mkt_org_busi_branch', value: mkt_org_busi_branch }) : ''
      if (this.filterData.length > 0) {
        this.filterData[this.filterData.length - 1].name = companyName
        this.initOpertion('drill')
      } else {
        // 如果维度为空,默认为交叉
        this.initOpertion('pivot')
      }
      this.DetailDataJson.filters = this.filterData
      this.idContent.push(id)
    },
    // 点击返回按钮
    onClickLeft() {
      this.dataCtl()
    },
    // 初始化数据
    initContent() {
      document.documentElement.scrollTop = 0
      this.DetailDataJson.page = 1
      this.listContent = []
    },
    /** 点击返回数据处理函数 */
    dataCtl() {
      if (this.dataContent.length > 1) {
        this.openLoading()
        // 当前删除的层操作类型
        const currentOperation = this.operationContent.pop()
        setTimeout(() => {
          const ocl = this.operationContent.length
          this.clearLoading()
          // 上层的操作类型
          if (currentOperation === 'attribution') {
            // 如果当前层操作为归因，TODO
            // 看返回那层是什么
            if (this.operationContent[ocl - 1] === 'attribution') {
              // 返回层也为归因，暂无该场景啥也不用做
            } else {
              // 返回那层为下钻或交叉，得做点什么
              this.dataContent.pop()
              this.defineData = this.dataContent[this.dataContent.length - 1]
              // 以下两个是有问题，
              // this.lastOperation === 'drill' ? this.filedActiveId.splice(-1) : this.filedActiveId.splice(-2)
              // this.lastOperation === 'drill' ? this.filterData.splice(-1) : this.filterData.splice(-2)
            }
          } else {
            // 如果当前层操作为下钻或者交叉，TODO
            // 看返回那层是什么
            if (this.operationContent[ocl - 1] === 'attribution') {
              // 返回层为归因，重置下数据，显示图表
              this.initContent()
              this.isShowPopup = false
              this.echartsRadarData = JSON.parse(JSON.stringify(this.echartsRadarDataContent.pop()))
              this.dataContent.pop()
              this.defineData = this.dataContent[this.dataContent.length - 1]
              this.clearLoading()
              this.notDataImage = false

              currentOperation === 'drill' ? this.filedActiveId.splice(-1) : this.filedActiveId.splice(-2)
              currentOperation === 'drill' ? this.filterData.splice(-1) : this.filterData.splice(-2)
            } else {
              // 返回那层为下钻或交叉
              this.dataContent.pop()
              this.defineData = this.dataContent[this.dataContent.length - 1]
              this.initContent()
              this.isShowPopup = false
              this.dateTypes.pop()
              this.titleDimContent.pop()
              this.idContent.pop()
              this.notDataImage = false

              currentOperation === 'drill' ? this.filedActiveId.splice(-1) : this.filedActiveId.splice(-2)
              currentOperation === 'drill' ? this.filterData.slice(-1) : this.filterData.slice(-2)

              const queryParams = JSON.parse(JSON.stringify(this.DetailDataJson))
              this.dateType = this.dateTypes[this.dateTypes.length - 1]
              queryParams.dateType = this.dateType
              queryParams.id = this.idContent[this.idContent.length - 1]
              queryParams.fields = this.filedActiveId
              queryParams.filters = this.filterData
              queryParams.operation = this.operationContent[this.operationContent.length - 1]
              this.getTendencyData(queryParams)
              this.getTrackStatus()
            }
          }

          // if (this.operationContent[ocl - 1] === 'attribution') {
          //   this.initContent()
          //   this.isShowPopup = false
          //   this.echartsRadarData = JSON.parse(
          //     JSON.stringify(this.echartsRadarDataContent[this.echartsRadarDataContent.length - 1])
          //   )
          //   this.dataContent.pop()
          //   this.echartsRadarDataContent.pop()
          //   this.defineData = this.dataContent[this.dataContent.length - 1]
          //   this.clearLoading()
          //   this.notDataImage = false
          // } else {
          //   this.dataContent.pop()
          //   this.defineData = this.dataContent[this.dataContent.length - 1]
          //   if (currentOperation !== 'attribution') {
          //     this.initContent()
          //     this.isShowPopup = false
          //     this.dateTypes.pop()
          //     this.titleDimContent.pop()
          //     this.idContent.pop()
          //     this.notDataImage = false
          //     this.filedActiveId =
          //       currentOperation === 'drill'
          //         ? this.filedActiveId.slice(0, filLth - 1)
          //         : this.filedActiveId.slice(0, filLth - 2)
          //     this.filterData =
          //       currentOperation === 'drill'
          //         ? this.filterData.slice(0, this.filterData.length - 1)
          //         : this.filterData.slice(0, this.filterData.length - 2)
          //     const queryParams = JSON.parse(JSON.stringify(this.DetailDataJson))
          //     this.dateType = this.dateTypes[this.dateTypes.length - 1]
          //     queryParams.dateType = this.dateType
          //     queryParams.id = this.idContent[this.idContent.length - 1]
          //     queryParams.fields = this.filedActiveId
          //     queryParams.filters = this.filterData
          //     queryParams.operation = this.operationContent[this.operationContent.length - 1]
          //     this.getTendencyData(queryParams)
          //     this.getTrackStatus()
          //   } else {
          //     console.log('watch, dataCtl this.lastOperation', this.lastOperation)
          //     console.log(this.filterData, ' this.filterData')
          //     this.lastOperation === 'drill' ? this.filedActiveId.splice(-1) : this.filedActiveId.splice(-2)
          //     // this.lastOperation === 'drill' ? this.filterData.splice(-1) : this.filterData.splice(-2)
          //   }
          //   this.clearLoading()
          // }
        }, 600)
      } else {
        // 当前页面返回方式
        // isAndroid || !this.$isDD ? this.$router.go(-1) : window.history.go(-1)
        // 打开新的页面关闭方式
        this.handleClose()
      }
    },
    // 打开新的关闭方式
    handleClose() {
      if (this.$isDD) {
        this.$dd.ready(() => {
          this.$dd.biz.navigation.close({})
        })
      } else {
        this.$router.back()
      }
    },
    trackButton() {
      // Toast.success('追踪成功')
    },
    onClickRight() {},
    /**
     * 点击下钻按钮（底部按钮+弹窗按钮）
     */
    handleDrilldownPuPDetermine(isClose, activeId, titleDim) {
      // 下钻
      this.isShowPopup = isClose
      this.modifyPup = 0
      // 返回顶部
      if (this.modifyFilter === false) {
        // 不是修改按钮
        this.defineData.fields.map(item => {
          if (item.role === 'dim') {
            this.filterData.push({
              code: item.refCode,
              value: this.overlapingItem[item.refCode],
              name: this.overlapingItem[item.logicCode]
            })
          }
        })
        this.idContent.push(this.overlapingItem.id)
        this.titleDimContent.push(titleDim)
        this.operationContent.push('drill')
      } else {
        const temp = [...this.operationContent]
        temp[temp.length - 1] = 'drill'
        this.operationContent = [...temp]
      }
      this.DetailDataJson.operation = 'drill'
      this.DetailDataJson.id = this.idContent[this.idContent.length - 1]
      this.DetailDataJson.fields = activeId
      this.DetailDataJson.filters = this.filterData
      this.DetailDataJson.operation = this.operationContent[this.operationContent.length - 1]
      this.dateType = this.DetailDataJson.dateType
      this.dateTypes.push(this.DetailDataJson.dateType)
      this.initContent()
      this.getDetailData(this.DetailDataJson)
      this.getTendencyData(this.DetailDataJson)
      // 下钻时重新获取追踪状态
      this.getTrackStatus()
      // 埋点
      this.drillDownToAnalyse(
        { fields: activeId, filters: this.filterData },
        {
          targetCode: this.targetCode
        }
      )
    },
    /**
     * 点击交叉（底部按钮+弹窗按钮）
     */
    handleOverLappingPuPDetermine(isClose, activeId, titleDim) {
      // 交叉
      this.isShowPopup = isClose
      this.modifyPup = 0
      // 初始化状态
      if (this.modifyFilter === false) {
        // 不是修改按钮
        this.defineData.fields.map(item => {
          if (item.role === 'dim') {
            this.filterData.push({
              code: item.refCode,
              value: this.overlapingItem[item.refCode],
              name: this.overlapingItem[item.logicCode]
            })
          }
        })
        this.idContent.push(this.overlapingItem.id)
        this.titleDimContent.push(titleDim)
        this.operationContent.push('pivot')
      } else {
        const temp = [...this.operationContent]
        temp[temp.length - 1] = 'pivot'
        this.operationContent = [...temp]
      }
      this.DetailDataJson.id = this.idContent[this.idContent.length - 1]
      this.DetailDataJson.fields = activeId
      this.DetailDataJson.filters = this.filterData
      this.DetailDataJson.operation = 'pivot'
      this.dateType = this.DetailDataJson.dateType
      this.dateTypes.push(this.DetailDataJson.dateType)
      this.initContent()
      this.getDetailData(this.DetailDataJson)
      this.getTendencyData(this.DetailDataJson)
      // 交叉时重新获取追踪状态
      this.getTrackStatus()
      // 埋点
      this.crossToAnalyse(
        { fields: activeId, filters: this.filterData },
        {
          targetCode: this.targetCode
        }
      )
    },
    // 加载更多
    handleScroll: _.throttle(function() {
      if (this.operationContent[this.operationContent.length - 1] === 'attribution') {
        return
      }
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      if (scrollTop + window.innerHeight >= document.body.offsetHeight - 10 && this.defineData.nolistTable === false) {
        this.DetailDataJson.page = this.DetailDataJson.page + 1
        this.DetailDataJson.id = this.idContent[this.idContent.length - 1]
        this.DetailDataJson.fields =
          this.operationContent[this.operationContent.length - 1] === 'drill'
            ? this.filedActiveId.slice(-1)
            : this.filedActiveId.slice(-2)
        this.DetailDataJson.filters = this.filterData
        this.DetailDataJson.operation = this.operationContent[this.operationContent.length - 1]
        this.getDetailData(this.DetailDataJson)
      }
    }, 1000),
    // loading效果打开
    openLoading() {
      this.$toast.loading({
        message: '加载中...',
        duration: 0,
        forbidClick: true
      })
    },
    // loading效果关闭
    clearLoading() {
      this.$toast.clear()
    },
    // 趋势图日期变化
    tendencyDateChange(date) {
      this.dateTypes[this.dateTypes.length - 1] = date
      this.getTendencyData(this.DetailDataJson, date)
    },
    // 获取详情信息
    async getDetailData(parmas) {
      this.openLoading()
      const res = await getDetailData(parmas)
      this.clearLoading()
      // 获取到接口的值，loading效果关闭
      if (res.errorCode === '0' && res.success) {
        // 判断接口状态
        const value = _.get(res, 'value', {})
        const fields = _.get(value, 'fields', [])
        this.primaryDataType = fields.find(m => m.role === 'measure' && m.type === 'primary').dataType
        this.fieldsDimlogicCode = fields.find(m => m.role === 'dim').logicCode
        if (this.modifyFilter) {
          console.log('watch, ', this.lastOperation)
          this.lastOperation === 'drill' ? this.filedActiveId.splice(-1) : this.filedActiveId.splice(-2)
        }
        fields.map(m => {
          if (m.role === 'dim') {
            this.filedActiveId.push({ code: m.refCode })
          }
        })
        this.lastOperation = parmas.operation
        if (this.filedActiveId.length === 0) {
          this.filedActiveId.unshift(...this.DetailDataJson.filters)
        }
        // 排序，默认主指标升序
        fields.map(item => {
          item.sortDown = false
          item.sortUp = false
          if (item.code === this.DetailDataJson.sortField && this.DetailDataJson.sort === 'ASC') {
            item.sortUp = true
          } else if (item.code === this.DetailDataJson.sortField && this.DetailDataJson.sort === 'DESC') {
            item.sortDown = true
          }
        })
        if (res.value.data.content.length < 200) {
          // 表示没有更多数据了，nolistTable为true显示文字提示
          res.value.nolistTable = true
        } else {
          res.value.nolistTable = false
        }
        // 加载更多，将每次加载的数据存放在listContent数组中
        this.listContent = this.listContent.concat(res.value.data.content)
        res.value.data.content = this.listContent
        if (this.modifyFilter === true) {
          // 修改
          this.defineData = res.value
          this.dataContent[this.dataContent.length - 1] = this.defineData
        } else if (this.modifyFilter === false) {
          // 下钻或交叉
          // 将之前上一层的数据存储，方便返回的时候展示
          this.dataContent.push(res.value)
          this.defineData = res.value
        }
      } else if (res.errorCode === '507') {
        this.notDataImage = true
      } else {
        // 数据异常
        this.dataContent.push({})
        this.defineData = {}
      }
      this.getTrackStatus()
    },
    // 获取维度信息
    async getPupOptionData() {
      let pupFilters = this.filterData
      if (this.modifyFilter === false && this.operationContent[this.operationContent.length - 1] === 'drill') {
        pupFilters = this.filterData.concat(this.filedActiveId.slice(-1))
      } else if (this.modifyFilter === false && this.operationContent[this.operationContent.length - 1] === 'pivot') {
        pupFilters = this.filterData.concat(this.filedActiveId.slice(-2))
      } else if (
        this.modifyFilter === false &&
        this.operationContent[this.operationContent.length - 1] === 'attribution'
      ) {
        if (this.operationContent[this.operationContent.length - 2] === 'drill') {
          pupFilters = this.filterData.concat(this.filedActiveId.slice(-1))
        } else if (this.operationContent[this.operationContent.length - 2] === 'pivot') {
          pupFilters = this.filterData.concat(this.filedActiveId.slice(-2))
        }
      } else if (this.modifyFilter === true) {
        pupFilters = this.filterData
      }
      const res = await getDimOptionsData({ source: this.DetailDataJson.topic, fields: pupFilters })
      if (res.errorCode === '0' && res.success === true) {
        try {
          const value = _.get(res, 'value', [])
          this.pupValue = value.filter(item => {
            // 返回child.status === 0
            item.childValue = item.childValue.filter(child => {
              if (child.status === 0) {
                child.text = child.name
                child.id = child.value
                return child
              }
            })
            item.text = item.dimName
            item.id = item.dimCode
            item.children = item.childValue
            // 子项没有时，父项也不返回
            if (item.childValue.length !== 0) {
              return item
            }
          })
        } catch (err) {
          console.log(err)
        }
      }
    },
    // 获取趋势图数据
    async getTendencyData(parmas, date) {
      const params_ = JSON.parse(JSON.stringify(parmas))
      if (date) {
        params_.dateType = date
        this.dateType = date
      }
      this.openLoading()
      const res = await queryTendencyData(params_)
      this.clearLoading()
      if (res.errorCode === '0' && res.success === true) {
        this.tendencyData = res.value
      } else {
        this.tendencyData = null
      }
    },
    // 归因分析
    async getAttribution(type) {
      const attributionParams = JSON.parse(JSON.stringify(this.DetailDataJson))
      const attributionFilter = []
      let newFilter = []
      if (type === 'edit') {
        this.defineData.fields.map(item => {
          if (item.role === 'dim') {
            attributionFilter.push({
              code: item.refCode,
              value: this.overlapingItem[item.refCode],
              name: this.overlapingItem[item.name]
            })
          }
        })
        this.operationContent.push('attribution')
      } else {
        const temp = [...this.operationContent]
        temp[temp.length - 1] = 'attribution'
        this.operationContent = temp
      }
      newFilter = [...this.filterData, ...attributionFilter]
      if (type === 'modify' && this.DetailDataJson.filters.length === 0) {
        newFilter = []
      } else if (type === 'modify' && this.DetailDataJson.filters.length > 1) {
        newFilter = this.filterData
      }
      attributionParams.fields = []
      attributionParams.filters = newFilter
      this.isShowPopup = false
      this.operationContent.push('attribution')
      this.dateType = this.DetailDataJson.dateType
      this.dateTypes.push(this.DetailDataJson.dateType)
      const res = await queryAttribution(attributionParams)
      if (res.errorCode === '507') {
        this.echartsRadarData.indicator = []
        this.echartsRadarData.reference = []
      } else {
        this.echartsRadarData = res.value
      }
      if (attributionParams.fields.length === 0 && attributionParams.filters.length === 0) {
        this.echartsRadarData.initValueType = '当前值'
      }
      this.echartsRadarDataContent.push(this.echartsRadarData)
      this.dataContent.push({})
    },
    getCurrentTrackParams() {
      const fields = _.get(this.defineData, 'fields', [])
      const headerContent = _.get(this.defineData, 'header', {})
      const logicCode = fields.find(m => m.role === 'measure' && m.type === 'primary').logicCode
      const headerNumber = headerContent[logicCode]
      const params = {
        comparedValue: this.secondaryNum,
        snapshotTime: this.DetailDataJson.queryDate,
        avatorUrl: this.userInfo?.avatar,
        indexValue: headerNumber + '',
        summarizingKey: this.DetailDataJson.targetCode,
        dateType: this.DetailDataJson.dateType,
        dimensionInfoList: this.filterData.length ? this.filterData : [{ code: 'mkt_org_branch', value: 'all' }]
      }
      return params
    },
    // 获取当前维度数据追踪状态
    async getTrackStatus() {
      const params = this.getCurrentTrackParams()
      const res = await traceStatus(params)
      if (res.value && res.success) {
        this.istracked = true
      } else {
        this.istracked = false
      }
    },
    handleTouch(e) {
      e._isScroller = true
    }
  }
}
</script>

<style lang="scss" scoped>
.indexAnalysisData_container {
  // margin-top: 46px;
}
/deep/.van-sidebar-item--select::before {
  background-color: $main-blue;
}
.indexAnalysis-container {
  -webkit-overflow-scrolling: touch !important;
  display: block;
  padding-bottom: 114px;
  // height: auto !important;
  .data_container {
    min-height: 101%;
    padding: 0 20px;
  }
  .loading {
    position: fixed;
    top: 50%;
    left: 50%;
  }
  .noListTable {
    text-align: center;
    font-size: 14px;
    margin-top: 10px;
    color: rgba(255, 255, 255, 0.5);
  }
}
.noData-container {
  width: 375px;
  .noData {
    width: 180px;
    height: 167px;
    margin: 175px auto 0px;
    display: block;
  }
  .noDataMessage {
    text-align: center;
    font-weight: 400;
    color: rgba(233, 233, 237, 0.64);
    line-height: 20px;
    font-size: 14px;
    padding-top: 5px;
  }
}
</style>
